<template>
  <a-modal
    v-model:open="open"
    title="片段剪辑"
    @ok="handleOk"
    @cancel="handleCancel"
    :okText="'导出视频'"
    :cancelText="'取消'"
    width="100%"
    destroyOnClose
    :confirm-loading="isLoading"
    :maskClosable="false"
  >
    <div class="video-container">
      <video
        id="video"
        ref="videoPlayer"
        :src="videoSrc"
        class="video-class"
        @timeupdate="handelTimeUpdate"
        :disabled="isLoading"
      />
      <canvas
        ref="drawCanvas"
        class="draw-canvas"
        :class="{ drawing: isDrawing, editing: !isDrawing }"
        @mousedown="startDrawing"
        @mousemove="drawing"
        @mouseup="stopDrawing"
        @mouseleave="stopDrawing"
      />
      <div class="current-time">{{ currentTimeDisplay }}</div>
      <div class="video-controls">
        <a-button-group>
          <a-button @click="togglePlay">
            <template #icon>
              <PlayCircleOutlined v-if="!isPlaying" />
              <PauseCircleOutlined v-else />
            </template>
          </a-button>
          <a-button @click="toggleMute">
            <template #icon>
              <AudioOutlined v-if="!isMuted" />
              <AudioMutedOutlined v-else />
            </template>
          </a-button>
          <a-select v-model:value="playbackRate" style="width: 100px" @change="handlePlaybackRateChange">
            <a-select-option v-for="rate in playbackRates" :key="rate" :value="rate"> {{ rate }}x </a-select-option>
          </a-select>
          <a-select v-model:value="drawColor" style="width: 100px" @change="handleColorChange">
            <a-select-option v-for="color in colors" :key="color.value" :value="color.value">
              {{ color.label }}
            </a-select-option>
          </a-select>
          <a-tooltip :title="isDrawing ? '退出绘制四边形' : '绘制四边形'">
            <a-button @click="toggleDrawMode" :class="{ 'draw-mode-active': isDrawing }">
              <template #icon>
                <BorderOutlined />
              </template>
            </a-button>
          </a-tooltip>
          <a-tooltip :title="isDrawingCurve ? '退出绘制曲线箭头' : '绘制曲线箭头'">
            <a-button @click="toggleCurveMode" :class="{ 'draw-mode-active': isDrawingCurve }">
              <template #icon>
                <ArrowRightOutlined />
              </template>
            </a-button>
          </a-tooltip>

          <a-tooltip :title="isDrawingDashedCurve ? '退出绘制虚线箭头' : '绘制虚线箭头'">
            <a-button @click="toggleDashedCurveMode" :class="{ 'draw-mode-active': isDrawingDashedCurve }">
              <template #icon>
                <DashOutlined />
              </template>
            </a-button>
          </a-tooltip>
        </a-button-group>
      </div>
    </div>
    <a-slider
      range
      v-model:value="timeRange"
      :max="videoDuration"
      :tip-formatter="formatter"
      @change="onChange"
      @afterChange="onAfterChange"
      :disabled="isLoading"
      :step="0.1"
    />
    <div class="spin-class" v-if="isLoading">
      <a-spin :tip="loadingTip" size="large" />
    </div>
  </a-modal>
</template>

<script lang="ts">
import { toRefs, defineComponent, reactive, ref, nextTick, computed } from "vue";
import {
  CloseOutlined,
  PlayCircleOutlined,
  PauseCircleOutlined,
  AudioOutlined,
  AudioMutedOutlined,
  BorderOutlined,
  ArrowRightOutlined,
  DashOutlined,
} from "@ant-design/icons-vue";
import { message } from "ant-design-vue";

interface Point {
  x: number;
  y: number;
}

interface Quadrilateral {
  points: Point[];
  color: string;
  startTime: number;
  endTime: number;
  finalPoints: Point[];
  isVisible: boolean;
  shouldPause: boolean;
}

interface CurveArrow {
  startPoint: Point;
  controlPoint: Point;
  endPoint: Point;
  color: string;
  startTime: number;
  endTime: number;
  isVisible: boolean;
  shouldPause: boolean;
}

// 虚线箭头与曲线箭头结构一致，使用相同类型
interface DashedCurveArrow {
  startPoint: Point;
  controlPoint: Point;
  endPoint: Point;
  color: string;
  startTime: number;
  endTime: number;
  isVisible: boolean;
  shouldPause: boolean;
}

export default defineComponent({
  name: "VideoCutModal",
  components: {
    CloseOutlined,
    PlayCircleOutlined,
    PauseCircleOutlined,
    AudioOutlined,
    AudioMutedOutlined,
    BorderOutlined,
    ArrowRightOutlined,
    DashOutlined,
  },

  setup(_) {
    const dataProps = reactive({
      isLoading: false,
      loadingTip: "视频处理中...",
      tagTime: null as any,
      tagTitle: "" as any,
      isPlaying: false,
      isMuted: false,
      playbackRate: 1.0,
      playbackRates: [0.1, 0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0],
      currentTime: 0,
      drawColor: "#FFD700",
      colors: [
        { label: "黄色", value: "#FFD700" },
        { label: "白色", value: "#FFFFFF" },
        { label: "红色", value: "#FF0000" },
        { label: "绿色", value: "#00FF00" },
        { label: "蓝色", value: "#0000FF" },
      ],
      quadrilaterals: [] as Quadrilateral[],
      curves: [] as CurveArrow[],
      dashedCurves: [] as DashedCurveArrow[],
      selectedQuadIndex: -1,
      selectedCurveIndex: -1,
      selectedDashedCurveIndex: -1,
      selectedPointIndex: -1,
      currentQuadStartTime: 0,
    });
    const drawingState = reactive({
      isDrawing: false,
      isDrawingCurve: false,
      isDrawingDashedCurve: false,
    });
    const open = ref<boolean>(false);
    const videoSrc = ref<string>(""); // 视频源地址
    const videoPlayer = ref(null) as any;
    const videoFile = ref<any>(null);
    const timeRange = ref([0, 0]); // 开始和结束时间
    const videoDuration = ref(0); // 视频总时长

    const currentTimeDisplay = computed(() => {
      return formatter(dataProps.currentTime);
    });

    const handleCancel = () => {
      // 清除所有图形
      dataProps.quadrilaterals = [];
      dataProps.curves = [];
      dataProps.dashedCurves = [];
      // 重置画布
      if (canvasContext.value && drawCanvas.value) {
        canvasContext.value.clearRect(0, 0, drawCanvas.value.width, drawCanvas.value.height);
      }
      // 重置其他状态
      dataProps.isLoading = false;
      dataProps.isPlaying = false;
      drawingState.isDrawing = false;
      drawingState.isDrawingCurve = false;
      dataProps.selectedQuadIndex = -1;
      dataProps.selectedCurveIndex = -1;
      dataProps.selectedDashedCurveIndex = -1;
      dataProps.selectedPointIndex = -1;
      startPoint.value = null;
      currentPoint.value = null;
      // 关闭弹框
      open.value = false;
    };
    const openModal = (item: number, tagTitle: string, videoUrl: any, videoFile: any) => {
      console.log("openModal===", item, videoUrl, videoFile);
      dataProps.tagTime = item;
      dataProps.tagTitle = tagTitle;
      videoSrc.value = videoUrl;
      videoFile.value = videoFile;
      open.value = true;

      nextTick(() => {
        initCanvas(); // 立即初始化画布
        const video = videoPlayer.value as HTMLVideoElement;
        video.addEventListener("loadedmetadata", () => {
          videoDuration.value = video.duration;
          timeRange.value = [0, video.duration];
          dataProps.isPlaying = false;
          dataProps.isMuted = video.muted;
          dataProps.playbackRate = video.playbackRate;
        });
        jumpToTime(item);
      });
    };
    // 跳转到指定时间
    const jumpToTime = (time: number) => {
      const video = videoPlayer.value as HTMLVideoElement;
      video.currentTime = time;
      setTimeout(() => {
        timeRange.value = [
          time - 1 > 0 ? Number((time - 1).toFixed(0)) : 0,
          time + 1 > video.duration ? video.duration : Number((time + 1).toFixed(0)),
        ];
        video.play();
        dataProps.isPlaying = true;
      }, 100);
    };
    const formatter = (value: number) => {
      let hours = Math.floor(value / 3600);
      let minutes = Math.floor((value % 3600) / 60);
      let secs = Math.floor(value % 60); // 确保秒数为整数
      // 时分秒补零
      let pad = (num: number) => String(num).padStart(2, "0");

      let timeString = "";

      if (hours > 0) {
        timeString += `${pad(hours)}时`;
      }
      if (minutes > 0 || hours > 0) {
        // 如果有小时或分钟，才显示分钟部分
        timeString += `${pad(minutes)}分`;
      }
      timeString += `${pad(secs)}秒`;

      return timeString;
    };

    const handelTimeUpdate = (event: Event) => {
      console.log(event);
      if (!videoPlayer.value) return;
      const currentTime = videoPlayer.value.currentTime;
      dataProps.currentTime = currentTime;

      // 检查是否需要在某个四边形或曲线箭头处暂停
      [...dataProps.quadrilaterals, ...dataProps.curves, ...dataProps.dashedCurves].forEach((shape) => {
        // 更新图形的可见性
        if (currentTime >= shape.startTime && currentTime <= shape.endTime) {
          shape.isVisible = true;
          if ("points" in shape) {
            shape.points = [...shape.finalPoints];
          }
        } else {
          shape.isVisible = false;
          if ("points" in shape) {
            shape.points = [];
          }
        }

        // 检查是否需要暂停
        if (Math.abs(currentTime - shape.startTime) < 0.1 && shape.shouldPause) {
          videoPlayer.value.pause();
          dataProps.isPlaying = false;
          shape.shouldPause = false;
          // 确保在暂停时显示图形
          shape.isVisible = true;
          if ("points" in shape) {
            shape.points = [...shape.finalPoints];
          }
          drawShapes();
        }
      });

      if (currentTime >= timeRange.value[1]) {
        videoPlayer.value.currentTime = timeRange.value[0];
        // 重置所有图形的暂停标志
        [...dataProps.quadrilaterals, ...dataProps.curves, ...dataProps.dashedCurves].forEach((shape) => {
          shape.shouldPause = true;
          shape.isVisible = false;
          if ("points" in shape) {
            shape.points = [];
          }
        });
        drawShapes();
      }
    };
    const onChange = (value: number) => {
      console.log("onChange: ", value);
    };

    const onAfterChange = (value: number) => {
      console.log(value);
      console.log("afterChange: ", timeRange.value);
      videoPlayer.value.currentTime = timeRange.value[0];
    };
    const handleOk = async () => {
      // const [start, end] = timeRange.value;
      // console.log("start===", start);
      // console.log("end===", end);
      // dataProps.isLoading = true;

      // try {
      //   // 创建离屏画布用于合成
      //   const offscreenCanvas = document.createElement("canvas");
      //   const offscreenCtx = offscreenCanvas.getContext("2d");
      //   if (!offscreenCtx) {
      //     throw new Error("无法创建画布上下文");
      //   }

      //   // 设置离屏画布尺寸
      //   offscreenCanvas.width = drawCanvas.value!.width;
      //   offscreenCanvas.height = drawCanvas.value!.height;

      //   // 使用主视频元素进行处理
      //   const video = videoPlayer.value;
      //   video.currentTime = start;

      //   // 等待视频就绪
      //   await new Promise((resolve) => {
      //     video.onseeked = resolve;
      //   });

      //   // 创建媒体流和录制器
      //   const stream = offscreenCanvas.captureStream(30); // 30fps
      //   const recorder = new MediaRecorder(stream, {
      //     mimeType: "video/webm;codecs=vp9",
      //     videoBitsPerSecond: 2500000,
      //   });
      //   const chunks: Blob[] = [];

      //   // 开始录制
      //   recorder.start();

      //   let isRecording = true;
      //   let lastProgressUpdate = Date.now();
      //   const fps = 30;
      //   let currentTime = start;

      //   const processFrame = async () => {
      //     if (!isRecording) return;

      //     // 更新进度显示
      //     const now = Date.now();
      //     if (now - lastProgressUpdate > 1000) {
      //       const progress = ((currentTime - start) / (end - start)) * 100;
      //       // message.info(`视频处理进度: ${Math.round(progress)}%`);
      //       dataProps.loadingTip = `视频处理中...: ${Math.round(progress)}%`;
      //       lastProgressUpdate = now;
      //     }

      //     // 检查是否到达结束时间
      //     if (currentTime >= end) {
      //       isRecording = false;
      //       recorder.stop();
      //       return;
      //     }

      //     // 设置视频时间
      //     video.currentTime = currentTime;
      //     await new Promise((resolve) => {
      //       video.onseeked = resolve;
      //     });

      //     // 在离屏画布上绘制当前帧
      //     offscreenCtx.clearRect(0, 0, offscreenCanvas.width, offscreenCanvas.height);
      //     offscreenCtx.drawImage(video, 0, 0, offscreenCanvas.width, offscreenCanvas.height);

      //     // 检查并绘制图形
      //     [...dataProps.quadrilaterals, ...dataProps.curves].forEach((shape) => {
      //       // 检查是否在图形的显示时间范围内（显示1秒）
      //       if (currentTime >= shape.startTime && currentTime <= shape.startTime + 1) {
      //         if ("points" in shape) {
      //           // 绘制四边形
      //           drawQuad(offscreenCtx, {
      //             points: shape.finalPoints,
      //             color: shape.color,
      //             isVisible: true,
      //           });
      //         } else {
      //           // 绘制曲线箭头
      //           drawCurve(offscreenCtx, {
      //             ...shape,
      //             isVisible: true,
      //           });
      //         }
      //       }
      //     });

      //     // 更新时间
      //     currentTime += 1 / fps;

      //     // 继续下一帧
      //     processFrame();
      //   };

      //   // 开始处理帧
      //   processFrame();

      //   recorder.ondataavailable = (e) => {
      //     if (e.data.size > 0) {
      //       chunks.push(e.data);
      //     }
      //   };

      //   recorder.onstop = () => {
      //     const blob = new Blob(chunks, { type: "video/webm" });
      //     const url = URL.createObjectURL(blob);
      //     downloadBlob(url);
      //     dataProps.isLoading = false;
      //     message.success("视频导出完成");
      //   };
      // } catch (error) {
      //   console.error("导出错误:", error);
      //   message.error("视频导出失败");
      //   dataProps.isLoading = false;
      // }

      const [start, end] = timeRange.value;
      console.log("start===", start);
      console.log("end===", end);
      dataProps.isLoading = true;
      const stream = (videoPlayer.value as any).captureStream();
      const recorder = new MediaRecorder(stream);
      const chunks: Blob[] = [];
      recorder.ondataavailable = (e) => chunks.push(e.data);
      recorder.start();
      videoPlayer.value.currentTime = start;
      await new Promise((resolve) => (videoPlayer.value!.ontimeupdate = resolve));

      setTimeout(() => {
        recorder.stop();
        videoPlayer.value!.ontimeupdate = null;
      }, (end - start) * 1000);

      recorder.onstop = () => {
        const blob = new Blob(chunks, { type: "video/webm" });
        const url = URL.createObjectURL(blob);
        downloadBlob(url);
      };
    };

    // 自动下载结果
    const downloadBlob = (url: string) => {
      const a = document.createElement("a");
      a.href = url;
      a.download = `${dataProps.tagTitle}-${formatter(dataProps.tagTime)}.mp4`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      dataProps.isLoading = false;
      open.value = false;
      message.success("剪辑成功且保存到本地");
    };

    const togglePlay = () => {
      if (videoPlayer.value) {
        if (dataProps.isPlaying) {
          videoPlayer.value.pause();
        } else {
          // 当用户点击播放时，隐藏所有图形
          [...dataProps.quadrilaterals, ...dataProps.curves, ...dataProps.dashedCurves].forEach((shape) => {
            shape.isVisible = false;
            if ("points" in shape) {
              shape.points = [];
            }
          });
          drawShapes();
          videoPlayer.value.play();
        }
        dataProps.isPlaying = !dataProps.isPlaying;
      }
    };

    const toggleMute = () => {
      if (videoPlayer.value) {
        videoPlayer.value.muted = !videoPlayer.value.muted;
        dataProps.isMuted = videoPlayer.value.muted;
      }
    };

    const handlePlaybackRateChange = (rate: number) => {
      if (videoPlayer.value) {
        videoPlayer.value.playbackRate = rate;
        dataProps.playbackRate = rate;
      }
    };

    const toggleDrawMode = () => {
      if (drawingState.isDrawing) {
        // 退出绘制模式
        drawingState.isDrawing = false;
        message.info("已退出绘制模式");
      } else {
        // 进入绘制模式
        if (videoPlayer.value) {
          videoPlayer.value.pause();
          dataProps.isPlaying = false;
        }
        drawingState.isDrawing = true;
        dataProps.currentQuadStartTime = videoPlayer.value ? videoPlayer.value.currentTime : 0;
        message.info("已进入绘制模式");
      }
    };

    const toggleCurveMode = () => {
      if (drawingState.isDrawingCurve) {
        // 退出绘制模式
        drawingState.isDrawingCurve = false;
        message.info("已退出绘制曲线箭头模式");
      } else {
        // 进入绘制模式
        if (videoPlayer.value) {
          videoPlayer.value.pause();
          dataProps.isPlaying = false;
        }
        drawingState.isDrawingCurve = true;
        dataProps.currentQuadStartTime = videoPlayer.value ? videoPlayer.value.currentTime : 0;
        message.info("已进入绘制曲线箭头模式");
      }
    };

    const toggleDashedCurveMode = () => {
      if (drawingState.isDrawingDashedCurve) {
        drawingState.isDrawingDashedCurve = false;
        message.info("已退出绘制虚线箭头模式");
      } else {
        if (videoPlayer.value) {
          videoPlayer.value.pause();
          dataProps.isPlaying = false;
        }
        drawingState.isDrawingDashedCurve = true;
        dataProps.currentQuadStartTime = videoPlayer.value ? videoPlayer.value.currentTime : 0;
        message.info("已进入绘制虚线箭头模式");
      }
    };

    const startDrawing = (event: MouseEvent) => {
      if (!drawCanvas.value || !canvasContext.value) return;

      const rect = drawCanvas.value.getBoundingClientRect();
      const x = event.clientX - rect.left;
      const y = event.clientY - rect.top;

      if (drawingState.isDrawing) {
        // 绘制四边形模式
        startPoint.value = { x, y };
        currentPoint.value = { x, y };
        drawShapes();
      } else if (drawingState.isDrawingCurve) {
        // 绘制曲线箭头模式
        startPoint.value = { x, y };
        currentPoint.value = { x, y };
        drawShapes();
      } else if (drawingState.isDrawingDashedCurve) {
        // 绘制虚线箭头模式
        startPoint.value = { x, y };
        currentPoint.value = { x, y };
        drawShapes();
      } else {
        // 编辑模式
        // 检查是否点击了曲线
        const clickedCurve = findClickedCurve(x, y);
        if (clickedCurve !== -1) {
          dataProps.selectedCurveIndex = clickedCurve;
          dataProps.selectedQuadIndex = -1;
          startPoint.value = { x, y };
          currentPoint.value = { x, y };
          return;
        }

        // 检查是否点击了虚线曲线
        const clickedDashed = findClickedDashedCurve(x, y);
        if (clickedDashed !== -1) {
          dataProps.selectedDashedCurveIndex = clickedDashed;
          dataProps.selectedCurveIndex = -1;
          dataProps.selectedQuadIndex = -1;
          startPoint.value = { x, y };
          currentPoint.value = { x, y };
          return;
        }

        // 检查是否点击了已存在的四边形的顶点
        const clickedPoint = findClickedPoint(x, y);
        if (clickedPoint) {
          dataProps.selectedQuadIndex = clickedPoint.quadIndex;
          dataProps.selectedPointIndex = clickedPoint.pointIndex;
          startPoint.value = { x, y };
          currentPoint.value = { x, y };
          drawShapes();
          return;
        }

        // 检查是否点击了四边形的内部
        const clickedQuad = findClickedQuad(x, y);
        if (clickedQuad !== -1) {
          dataProps.selectedQuadIndex = clickedQuad;
          dataProps.selectedPointIndex = -1;
          startPoint.value = { x, y };
          currentPoint.value = { x, y };
          drawShapes();
          return;
        }
      }
    };

    const drawing = (event: MouseEvent) => {
      if (!startPoint.value || !drawCanvas.value || !canvasContext.value) return;

      const rect = drawCanvas.value.getBoundingClientRect();
      const x = event.clientX - rect.left;
      const y = event.clientY - rect.top;

      currentPoint.value = { x, y };

      if (drawingState.isDrawing) {
        // 绘制四边形
        drawShapes();
      } else if (drawingState.isDrawingCurve) {
        // 绘制曲线箭头
        drawShapes();
      } else if (drawingState.isDrawingDashedCurve) {
        // 绘制虚线箭头
        drawShapes();
      } else {
        // 编辑模式
        if (dataProps.selectedCurveIndex !== -1) {
          updateCurve();
        } else if (dataProps.selectedDashedCurveIndex !== -1) {
          updateDashedCurve();
        } else if (dataProps.selectedQuadIndex !== -1) {
          updateQuadrilateral();
        }
      }
    };

    const stopDrawing = () => {
      if (!startPoint.value || !currentPoint.value) return;

      const currentTime = videoPlayer.value ? videoPlayer.value.currentTime : 0;

      if (drawingState.isDrawing) {
        // 完成四边形绘制
        const points = calculateQuadrilateralPoints(startPoint.value, currentPoint.value);
        dataProps.quadrilaterals.push({
          points,
          color: dataProps.drawColor,
          startTime: dataProps.currentQuadStartTime,
          endTime: currentTime,
          finalPoints: [...points],
          isVisible: true,
          shouldPause: true,
        });
      } else if (drawingState.isDrawingCurve) {
        // 完成曲线箭头绘制
        const controlPoint = {
          x: (startPoint.value.x + currentPoint.value.x) / 2,
          y: startPoint.value.y - 50, // 控制点向上偏移，形成曲线
        };
        dataProps.curves.push({
          startPoint: { ...startPoint.value },
          controlPoint,
          endPoint: { ...currentPoint.value },
          color: dataProps.drawColor,
          startTime: dataProps.currentQuadStartTime,
          endTime: currentTime,
          isVisible: true,
          shouldPause: true,
        });
      } else if (drawingState.isDrawingDashedCurve) {
        // 完成虚线箭头绘制
        const controlPoint = {
          x: (startPoint.value.x + currentPoint.value.x) / 2,
          y: startPoint.value.y - 50,
        };
        dataProps.dashedCurves.push({
          startPoint: { ...startPoint.value },
          controlPoint,
          endPoint: { ...currentPoint.value },
          color: dataProps.drawColor,
          startTime: dataProps.currentQuadStartTime,
          endTime: currentTime,
          isVisible: true,
          shouldPause: true,
        });
      } else if (dataProps.selectedCurveIndex !== -1) {
        // 更新曲线位置
        const curve = dataProps.curves[dataProps.selectedCurveIndex];
        // 保存修改后的状态
        dataProps.curves[dataProps.selectedCurveIndex] = {
          ...curve,
          startPoint: { ...curve.startPoint },
          controlPoint: { ...curve.controlPoint },
          endPoint: { ...curve.endPoint },
        };
      } else if (dataProps.selectedDashedCurveIndex !== -1) {
        // 更新虚线箭头位置
        const curve = dataProps.dashedCurves[dataProps.selectedDashedCurveIndex];
        dataProps.dashedCurves[dataProps.selectedDashedCurveIndex] = {
          ...curve,
          startPoint: { ...curve.startPoint },
          controlPoint: { ...curve.controlPoint },
          endPoint: { ...curve.endPoint },
        };
      } else if (dataProps.selectedQuadIndex !== -1) {
        // 更新四边形位置
        const quad = dataProps.quadrilaterals[dataProps.selectedQuadIndex];
        quad.finalPoints = [...quad.points];
      }

      startPoint.value = null;
      currentPoint.value = null;
      dataProps.selectedQuadIndex = -1;
      dataProps.selectedCurveIndex = -1;
      dataProps.selectedDashedCurveIndex = -1;
      dataProps.selectedPointIndex = -1;
      drawShapes();
    };

    const findClickedPoint = (x: number, y: number): { quadIndex: number; pointIndex: number } | null => {
      const pointRadius = 5;
      for (let i = 0; i < dataProps.quadrilaterals.length; i++) {
        const quad = dataProps.quadrilaterals[i];
        for (let j = 0; j < quad.points.length; j++) {
          const point = quad.points[j];
          const distance = Math.sqrt(Math.pow(point.x - x, 2) + Math.pow(point.y - y, 2));
          if (distance <= pointRadius) {
            return { quadIndex: i, pointIndex: j };
          }
        }
      }
      return null;
    };

    const findClickedQuad = (x: number, y: number): number => {
      for (let i = 0; i < dataProps.quadrilaterals.length; i++) {
        const quad = dataProps.quadrilaterals[i];
        if (isPointInQuad(x, y, quad.points)) {
          return i;
        }
      }
      return -1;
    };

    const isPointInQuad = (x: number, y: number, points: Point[]): boolean => {
      let inside = false;
      for (let i = 0, j = points.length - 1; i < points.length; j = i++) {
        const xi = points[i].x;
        const yi = points[i].y;
        const xj = points[j].x;
        const yj = points[j].y;

        const intersect = yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi;
        if (intersect) inside = !inside;
      }
      return inside;
    };

    const updateQuadrilateral = () => {
      if (!canvasContext.value || !currentPoint.value || dataProps.selectedQuadIndex === -1) return;

      const quad = dataProps.quadrilaterals[dataProps.selectedQuadIndex];
      if (dataProps.selectedPointIndex !== -1) {
        // 更新控制点
        quad.points[dataProps.selectedPointIndex] = { ...currentPoint.value };
      } else {
        // 移动整个四边形
        const dx = currentPoint.value.x - startPoint.value!.x;
        const dy = currentPoint.value.y - startPoint.value!.y;
        quad.points = quad.points.map((point) => ({
          x: point.x + dx,
          y: point.y + dy,
        }));
        // 更新起始点
        startPoint.value = { ...currentPoint.value };
      }

      drawShapes();
    };

    const findClickedCurve = (x: number, y: number): number => {
      return dataProps.curves.findIndex((curve) => {
        if (!curve.isVisible) return false;
        // 检查是否在曲线附近
        const path = new Path2D();
        path.moveTo(curve.startPoint.x, curve.startPoint.y);
        path.quadraticCurveTo(curve.controlPoint.x, curve.controlPoint.y, curve.endPoint.x, curve.endPoint.y);
        return canvasContext.value?.isPointInStroke(path, x, y) || false;
      });
    };

    const findClickedDashedCurve = (x: number, y: number): number => {
      return dataProps.dashedCurves.findIndex((curve) => {
        if (!curve.isVisible) return false;
        const path = new Path2D();
        path.moveTo(curve.startPoint.x, curve.startPoint.y);
        path.quadraticCurveTo(curve.controlPoint.x, curve.controlPoint.y, curve.endPoint.x, curve.endPoint.y);
        return canvasContext.value?.isPointInStroke(path, x, y) || false;
      });
    };

    const drawCurve = (ctx: CanvasRenderingContext2D, curve: CurveArrow) => {
      ctx.beginPath();
      ctx.moveTo(curve.startPoint.x, curve.startPoint.y);
      ctx.quadraticCurveTo(curve.controlPoint.x, curve.controlPoint.y, curve.endPoint.x, curve.endPoint.y);

      // 设置线条样式
      ctx.strokeStyle = curve.color;
      ctx.lineWidth = 2;
      ctx.setLineDash([]); // 实线
      ctx.stroke();

      // 绘制箭头
      const angle = Math.atan2(curve.endPoint.y - curve.controlPoint.y, curve.endPoint.x - curve.controlPoint.x);
      const arrowLength = 10;

      ctx.beginPath();
      ctx.moveTo(curve.endPoint.x, curve.endPoint.y);
      ctx.lineTo(
        curve.endPoint.x - arrowLength * Math.cos(angle - Math.PI / 6),
        curve.endPoint.y - arrowLength * Math.sin(angle - Math.PI / 6),
      );
      ctx.lineTo(
        curve.endPoint.x - arrowLength * Math.cos(angle + Math.PI / 6),
        curve.endPoint.y - arrowLength * Math.sin(angle + Math.PI / 6),
      );
      ctx.closePath();
      ctx.fillStyle = curve.color;
      ctx.fill();

      // 绘制控制点
      ctx.beginPath();
      ctx.arc(curve.controlPoint.x, curve.controlPoint.y, 5, 0, Math.PI * 2);
      ctx.fillStyle = curve.color;
      ctx.fill();
      ctx.strokeStyle = "#fff";
      ctx.stroke();
    };

    const drawDashedCurve = (ctx: CanvasRenderingContext2D, curve: DashedCurveArrow) => {
      ctx.beginPath();
      ctx.moveTo(curve.startPoint.x, curve.startPoint.y);
      ctx.quadraticCurveTo(curve.controlPoint.x, curve.controlPoint.y, curve.endPoint.x, curve.endPoint.y);

      // 设置虚线样式
      ctx.strokeStyle = curve.color;
      ctx.lineWidth = 2;
      ctx.setLineDash([8, 6]);
      ctx.stroke();
      ctx.setLineDash([]);

      // 箭头采用实心，增强可视性
      const angle = Math.atan2(curve.endPoint.y - curve.controlPoint.y, curve.endPoint.x - curve.controlPoint.x);
      const arrowLength = 10;
      ctx.beginPath();
      ctx.moveTo(curve.endPoint.x, curve.endPoint.y);
      ctx.lineTo(
        curve.endPoint.x - arrowLength * Math.cos(angle - Math.PI / 6),
        curve.endPoint.y - arrowLength * Math.sin(angle - Math.PI / 6),
      );
      ctx.lineTo(
        curve.endPoint.x - arrowLength * Math.cos(angle + Math.PI / 6),
        curve.endPoint.y - arrowLength * Math.sin(angle + Math.PI / 6),
      );
      ctx.closePath();
      ctx.fillStyle = curve.color;
      ctx.fill();

      // 控制点
      ctx.beginPath();
      ctx.arc(curve.controlPoint.x, curve.controlPoint.y, 5, 0, Math.PI * 2);
      ctx.fillStyle = curve.color;
      ctx.fill();
      ctx.strokeStyle = "#fff";
      ctx.stroke();
    };

    const updateCurve = () => {
      if (!currentPoint.value || dataProps.selectedCurveIndex === -1) return;

      const curve = dataProps.curves[dataProps.selectedCurveIndex];
      const dx = currentPoint.value.x - startPoint.value!.x;
      const dy = currentPoint.value.y - startPoint.value!.y;

      // 更新控制点位置
      curve.controlPoint.x += dx;
      curve.controlPoint.y += dy;

      startPoint.value = { ...currentPoint.value };
      drawShapes();
    };

    const updateDashedCurve = () => {
      if (!currentPoint.value || dataProps.selectedDashedCurveIndex === -1) return;

      const curve = dataProps.dashedCurves[dataProps.selectedDashedCurveIndex];
      const dx = currentPoint.value.x - startPoint.value!.x;
      const dy = currentPoint.value.y - startPoint.value!.y;

      curve.controlPoint.x += dx;
      curve.controlPoint.y += dy;

      startPoint.value = { ...currentPoint.value };
      drawShapes();
    };

    const drawShapes = () => {
      if (!canvasContext.value || !drawCanvas.value) return;

      const ctx = canvasContext.value;
      ctx.clearRect(0, 0, drawCanvas.value.width, drawCanvas.value.height);

      // 绘制所有可见的四边形
      dataProps.quadrilaterals.forEach((quad) => {
        if (quad.isVisible && quad.points.length > 0) {
          drawQuad(ctx, quad);
        }
      });

      // 绘制所有可见的曲线箭头
      dataProps.curves.forEach((curve) => {
        if (curve.isVisible) {
          drawCurve(ctx, curve);
        }
      });

      // 绘制所有可见的虚线箭头
      dataProps.dashedCurves.forEach((curve) => {
        if (curve.isVisible) {
          drawDashedCurve(ctx, curve);
        }
      });

      // 绘制临时图形
      if (startPoint.value && currentPoint.value) {
        if (drawingState.isDrawing) {
          // 绘制临时四边形
          const points = calculateQuadrilateralPoints(startPoint.value, currentPoint.value);
          drawQuad(ctx, { points, color: dataProps.drawColor, isVisible: true });
        } else if (drawingState.isDrawingCurve) {
          // 绘制临时曲线箭头
          const controlPoint = {
            x: (startPoint.value.x + currentPoint.value.x) / 2,
            y: startPoint.value.y - 50, // 控制点向上偏移，形成曲线
          };
          drawCurve(ctx, {
            startPoint: startPoint.value,
            controlPoint,
            endPoint: currentPoint.value,
            color: dataProps.drawColor,
            isVisible: true,
          } as CurveArrow);
        } else if (drawingState.isDrawingDashedCurve) {
          // 绘制临时虚线箭头
          const controlPoint = {
            x: (startPoint.value.x + currentPoint.value.x) / 2,
            y: startPoint.value.y - 50,
          };
          drawDashedCurve(ctx, {
            startPoint: startPoint.value,
            controlPoint,
            endPoint: currentPoint.value,
            color: dataProps.drawColor,
            isVisible: true,
          } as DashedCurveArrow);
        }
      }
    };

    const drawCanvas = ref<HTMLCanvasElement | null>(null);
    const canvasContext = ref<CanvasRenderingContext2D | null>(null);
    const startPoint = ref<Point | null>(null);
    const currentPoint = ref<Point | null>(null);

    const initCanvas = () => {
      if (!drawCanvas.value) {
        console.error("Canvas element not found");
        return;
      }

      const video = videoPlayer.value as HTMLVideoElement;
      if (!video) {
        console.error("Video element not found");
        return;
      }

      const container = video.parentElement;
      if (!container) {
        console.error("Video container not found");
        return;
      }

      // 设置画布尺寸
      drawCanvas.value.width = container.clientWidth;
      drawCanvas.value.height = container.clientHeight;

      // 获取画布上下文
      const ctx = drawCanvas.value.getContext("2d");
      if (!ctx) {
        console.error("Failed to get canvas context");
        return;
      }

      canvasContext.value = ctx;
      console.log("Canvas initialized:", {
        width: drawCanvas.value.width,
        height: drawCanvas.value.height,
        context: canvasContext.value,
      });
    };

    // 监听视频加载完成事件
    nextTick(() => {
      const video = videoPlayer.value as HTMLVideoElement;
      if (video) {
        video.addEventListener("loadedmetadata", () => {
          videoDuration.value = video.duration;
          timeRange.value = [0, video.duration];
          dataProps.isPlaying = false;
          dataProps.isMuted = video.muted;
          dataProps.playbackRate = video.playbackRate;
          initCanvas();
        });
        jumpToTime(dataProps.tagTime);
      }
    });

    // 监听窗口大小变化
    window.addEventListener("resize", () => {
      initCanvas();
      drawShapes();
    });

    const handleColorChange = (color: string) => {
      dataProps.drawColor = color;
    };

    const calculateQuadrilateralPoints = (start: Point, end: Point): Point[] => {
      const width = end.x - start.x;
      const height = end.y - start.y;
      return [
        { x: start.x, y: start.y },
        { x: start.x + width, y: start.y },
        { x: start.x + width, y: start.y + height },
        { x: start.x, y: start.y + height },
      ];
    };

    const drawQuad = (ctx: CanvasRenderingContext2D, quad: { points: Point[]; color: string; isVisible: boolean }) => {
      if (quad.points.length !== 4) return;

      ctx.beginPath();
      ctx.moveTo(quad.points[0].x, quad.points[0].y);
      for (let i = 1; i < quad.points.length; i++) {
        ctx.lineTo(quad.points[i].x, quad.points[i].y);
      }
      ctx.closePath();

      // 设置填充颜色和透明度
      ctx.fillStyle = quad.color + (quad.isVisible ? "30" : "00");
      ctx.fill();

      // 设置边框颜色
      ctx.strokeStyle = quad.color;
      ctx.lineWidth = 2;
      ctx.stroke();

      // 绘制控制点
      quad.points.forEach((point) => {
        ctx.beginPath();
        ctx.arc(point.x, point.y, 5, 0, Math.PI * 2);
        ctx.fillStyle = quad.color;
        ctx.fill();
        ctx.strokeStyle = "#fff";
        ctx.stroke();
      });
    };

    return {
      ...toRefs(dataProps),
      ...toRefs(drawingState),
      drawCanvas,
      currentTimeDisplay,
      open,
      handleCancel,
      openModal,
      handleOk,
      videoSrc,
      videoFile,
      videoPlayer,
      timeRange,
      videoDuration,
      jumpToTime,
      formatter,
      onChange,
      onAfterChange,
      handelTimeUpdate,
      togglePlay,
      toggleMute,
      handlePlaybackRateChange,
      toggleDrawMode,
      startDrawing,
      drawing,
      stopDrawing,
      handleColorChange,
      updateQuadrilateral,
      toggleCurveMode,
      toggleDashedCurveMode,
    };
  },
});
</script>

<style lang="less" scoped>
.video-container {
  position: relative;
  width: 100%;
}

.video-class {
  width: 100%;
  border-radius: 10px;
  height: 80vh;
  background-color: #313234;
  &::-webkit-media-controls {
    display: none !important;
  }
}

.current-time {
  position: absolute;
  top: 20px;
  left: 20px;
  background: rgba(0, 0, 0, 0.75);
  color: #fff;
  padding: 8px 16px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  backdrop-filter: blur(8px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  z-index: 10;
}

.video-controls {
  position: absolute;
  bottom: 20px;
  left: 20px;
  background: rgba(0, 0, 0, 0.75);
  padding: 12px 20px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  gap: 15px;
  z-index: 10;
  backdrop-filter: blur(8px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);

  :deep(.ant-btn-group) {
    display: flex;
    gap: 4px;
  }

  :deep(.ant-btn) {
    background: rgba(255, 255, 255, 0.1);
    border: none;
    color: #fff;
    width: 40px;
    height: 40px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
    margin: 0 !important;

    &:hover {
      background: rgba(255, 255, 255, 0.2);
      color: #fff;
    }

    &.draw-mode-active {
      background: rgba(255, 255, 255, 0.3);
      color: #1890ff;
      box-shadow: 0 0 8px rgba(24, 144, 255, 0.5);
    }

    .anticon {
      font-size: 20px;
    }
  }

  :deep(.ant-select) {
    width: 100px;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 8px;
    border: none;

    .ant-select-selector {
      background: transparent !important;
      border: none !important;
      height: 40px;
      padding: 0 12px;
      display: flex;
      align-items: center;

      .ant-select-selection-item {
        color: #fff;
      }
    }

    .ant-select-arrow {
      color: #fff;
    }

    &:hover {
      background: rgba(255, 255, 255, 0.15);
    }
  }

  :deep(.ant-select-dropdown) {
    background: #1f1f1f;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);

    .ant-select-item {
      color: #fff;
      padding: 8px 12px;
      border-radius: 4px;

      &:hover {
        background: rgba(255, 255, 255, 0.1);
      }

      &-option-selected {
        background: rgba(255, 255, 255, 0.15);
        color: #fff;
      }
    }
  }
}

.spin-class {
  position: absolute;
  left: 0;
  right: 0;
  width: 100%;
  background: rgba(0, 0, 0, 0.3);
  height: 100%;
  top: 0;
  text-align: center;
  align-items: center;
  display: flex;
  justify-content: center;
  z-index: 100;
  :deep(.ant-spin-text) {
    margin-top: 20px;
  }
}

.draw-canvas {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 5;

  &.drawing {
    pointer-events: auto;
    cursor: crosshair;
  }

  &.editing {
    pointer-events: auto;
    cursor: default;
  }
}
</style>
